package com.carlinfo.usercenter.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件工具类 
 * @author jjh
 *
 */
public class FileUtil
{
	/**
	 * 拷贝文件,参数是文件对象,不在是管子 
	 * @param souFile
	 * @param tarFile
	 * @return
	 */
	public boolean copy(File souFile, File tarFile)
	{
		try
		{
			FileInputStream fis = new FileInputStream(souFile);
			FileOutputStream fos = new FileOutputStream(tarFile);
			return this.copy(fis, fos);
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		return false ;
	}
	
	/**
	 * 拷贝文件 
	 * @param is
	 * @param os
	 * @return
	 */
	public boolean copy(InputStream is , OutputStream os)
	{
		/* 拷贝的时候使用粗管子 */
		BufferedInputStream bis = new BufferedInputStream(is);
		BufferedOutputStream bos = new BufferedOutputStream(os);
		
		/*
		 * 准备容器 
		 * 1024 * 1024 * 10 === 10m
		 */
		byte [] b = new byte[2 * 1024 * 1024] ;
		int len = 0 ;
		try
		{
			while((len = bis.read(b)) != -1)
			{
				bos.write(b,0,len);
			}
			/* 拷贝完成 */
			return true ;
		} catch (IOException e)
		{
			
			e.printStackTrace();
		}finally
		{
			try
			{
				if(bis != null)
				{
					bis.close();
					bis = null ;
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
			
			try
			{
				if(bos != null)
				{
					bos.close();
					bos = null ;
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		return false ;
	}
	
	public static void main(String[] args)
	{
		System.out.println("========");
		FileUtil fileUtil = new FileUtil();
		File souFile = new File("d:/test/jj.jpg");
		File tarFile = new File("d:/test/jj_01.jpg");
		fileUtil.copy(souFile, tarFile);
	}
}	
